<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/Apache-2.0
 * @link https://www.gougucms.com
 */
// 应用公共文件
use think\facade\Cache;
use think\facade\Config;
use think\facade\Db;
use think\facade\Request;
use think\exception\ValidateException;
use think\facade\Filesystem;

function success($msg,$data=array()){
    return json(['code'=>0,'msg'=>$msg,'data'=>$data]);
}

function error($msg){
    return json(['code'=>1,'msg'=>$msg]);
}

function dates()
{
    //获取日期
    $res =  get_weeks(time());
    $res = array_values($res);
    $arr = [];
    foreach ($res as $vv) {
        $arr[] = $vv['time'];
    }
    sort($arr);
    foreach ($arr as &$v) {
        $v = date('Y-m-d',$v);
    }
    return $arr;
}

function get_weeks($time = '', $format='Y-m-d'){
    $time = $time != '' ? $time : time();
    //组合数据
    $date = [];
    for ($i=0; $i<7; $i++){
        $date[$i]['date'] = date($format ,strtotime( '-' . $i .' days', $time));
        $date[$i]['dates'] = date('Y-m-d' ,strtotime( '-' . $i .' days', $time));
        if ($i == 0) {
            $date[$i]['week'] = '今天';
        } else {
            $date[$i]['week'] = get_week(date($format ,strtotime( '-' . $i .' days', $time)));
        }
        $date[$i]['time'] = strtotime( '-' . $i .' days', $time);
    }
    return $date;
}

function dateFive(){
    $res =  get_weeks_five(time());
    return array_values($res);
}

function get_weeks_five($time = '', $format='Y-m-d'){
    $time = $time != '' ? $time : time();
    //组合数据
    $date = [];
    for ($i=0; $i<5; $i++){
        $date[$i]['date'] = date($format ,strtotime( '-' . $i .' days', $time));
        $date[$i]['dates'] = date('Y-m-d' ,strtotime( '-' . $i .' days', $time));
        if ($i == 0) {
            $date[$i]['week'] = '今天';
        } else {
            $date[$i]['week'] = get_week(date($format ,strtotime( '-' . $i .' days', $time)));
        }
        $date[$i]['time'] = strtotime( '-' . $i .' days', $time);
    }
    return $date;
}

function dateFiveMonth(){
    $res =  get_month_five(time());
    return array_values($res);
}

function get_month_five($time = '', $format='Y-m-d'){
    $time = $time != '' ? $time : time();
    //组合数据
    $date = [];
    for ($i=0; $i<5; $i++){
        $date[$i]['date'] = date($format ,strtotime( '-' . $i .' month', $time));
        $month = $date[$i]['date'];
        $date[$i]['start_date'] = date('Y-m-d', mktime(00, 00, 00, date('m', strtotime($month)), 01));
        $date[$i]['end_date'] = date('Y-m-d', mktime(23, 59, 59, date('m', strtotime($month))+1, 00));
        $date[$i]['time'] = strtotime( '-' . $i .' month', $time);
    }
    return $date;
}

function dateFiveYear(){
    $res =  get_year_five(time());
    return array_values($res);
}

function get_year_five($time = '', $format='Y'){
    $time = $time != '' ? $time : time();
    //组合数据
    $date = [];
    for ($i=0; $i<5; $i++){
        $date[$i]['date'] = date($format ,strtotime( '-' . $i .' year', $time));
        $date[$i]['start_date'] = date('Y-m-d', strtotime($date[$i]['date'] . '-01-01'));
        $end_date = $date[$i]['date']+1;
        $date[$i]['end_date'] = $end_date.'-01-01';
        $date[$i]['time'] = strtotime( '-' . $i .' year', $time);
    }
    return $date;
}

function selCity($id){
    $dis = Db::name('city')->where('id',$id)->find();
    if (empty($dis)) {
        return '';
    }
    $city = Db::name('city')->where('id',$dis['pid'])->find();
    $pro = Db::name('city')->where('id',$city['pid'])->find();
    return $pro['name'].$city['name'].$dis['name'];
}

function zm($m){
    $arr = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q');
    return $arr[$m];
}

/***************************** 根据详细地址获取经纬度 **********************************/
function getLocation($addr){

    $url = "https://apis.map.qq.com/ws/geocoder/v1/?address=".$addr."&key=PTQBZ-CDSCB-JB5UO-JHOVV-OWCS2-JTFHT";
    $data_info = curl_get($url);
    $data_info = json_decode($data_info, true); //数据转换
    $data = [
        'lng' => 0,
        'lat' => 0
    ];
    if (!empty($data_info['status'])) {
        return $data;
    }

    $data['lng'] = $data_info['result']['location']['lng'];
    $data['lat'] = $data_info['result']['location']['lat'];
    return $data;
}

function getGeolocationFromCoordinates($latitude, $longitude) {
    $url = "https://apis.map.qq.com/ws/geocoder/v1/?location={$latitude},{$longitude}&key=CMIBZ-3C4WP-WOLDW-VSED3-AWGSQ-62BCQ";
    $response = curl_get($url);
    $data = json_decode($response, true);
    if ($data ['status'] == 0) {
        $address = $data['result']['address']; // 地址信息
        return json_encode(['code'=>0,'msg'=>$address],JSON_UNESCAPED_UNICODE);
    } else {
        return json_encode(['code'=>1,'msg'=>$data['message']],JSON_UNESCAPED_UNICODE);
    }
}


function get_format_time($time)
{
    $time = (int)substr($time, 0, 10);
    $int = time() - $time;
    $str = '';
    if ($int <= 2) {
        $str = sprintf('刚刚', $int);
    } elseif ($int < 60) {
        $str = sprintf('%d秒前', $int);
    } elseif ($int < 3600) {
        $str = sprintf('%d分钟前', floor($int / 60));
    } elseif ($int < 86400) {
        $str = sprintf('%d小时前', floor($int / 3600));
    } elseif ($int < 1728000) {
        $str = sprintf('%d天前', floor($int / 86400));
    } else {
        $str = date('Y年m月d日', $time);
    }
    return $str;
}

/**
 * 根据两地坐标计算距离
 */
function distanceBetween($lat1,$lon1,$lat2,$lon2){
    $lon1 = (pi() / 180) * $lon1;
    $lon2 = (pi() / 180) * $lon2;
    $lat1 = (pi() / 180) * $lat1;
    $lat2 = (pi() / 180) * $lat2;
    // 地球半径
    $R = 6371;
    // 两点间距离 km，如果想要米的话，结果*1000就可以了
    $d = acos(sin($lat1)*sin($lat2)+cos($lat1)*cos($lat2)*cos($lon2-$lon1))*$R;
    return round($d,2);
}
function get_week_date($date)
{
    //强制转换日期格式
    $date_str = date('Y-m-d', strtotime($date));
//    var_dump($date);exit();
    //封装成数组
    $arr = explode("-", $date_str);
    //参数赋值
    //年
    $year = $arr[0];
    //月，输出2位整型，不够2位右对齐
    $month = sprintf('%02d', $arr[1]);
    //日，输出2位整型，不够2位右对齐
    $day = sprintf('%02d', $arr[2]);
    //时分秒默认赋值为0；
    $hour = $minute = $second = 0;
    //转换成时间戳
    $strap = mktime($hour, $minute, $second, $month, $day, $year);
    //获取数字型星期几
    $number_wk = date("w", $strap);
    //自定义星期数组
    $weekArr = array("周日", "周一", "周二", "周三", "周四", "周五", "周六");
    //获取数字对应的星期
    return $weekArr[$number_wk];
}

function get_week($date)
{
    //强制转换日期格式
    $date_str = date('Y-m-d', strtotime($date));
//    var_dump($date);exit();
    //封装成数组
    $arr = explode("-", $date_str);
    //参数赋值
    //年
    $year = $arr[0];
    //月，输出2位整型，不够2位右对齐
    $month = sprintf('%02d', $arr[1]);
    //日，输出2位整型，不够2位右对齐
    $day = sprintf('%02d', $arr[2]);
    //时分秒默认赋值为0；
    $hour = $minute = $second = 0;
    //转换成时间戳
    $strap = mktime($hour, $minute, $second, $month, $day, $year);
    //获取数字型星期几
    $number_wk = date("w", $strap);
    //自定义星期数组
    $weekArr = array("日", "一", "二", "三", "四", "五", "六");
    //获取数字对应的星期
    return $weekArr[$number_wk];
}

//获取自然周日期（周一~周日）
function getDay()
{
    $timestr = time();    //当前时间戳
    $now_day = date('w',$timestr);  //当前是周几

    //获取周一
    $monday_str = $timestr - ($now_day-1)*60*60*24;
    $monday = date('Y-m-d', $monday_str);

    //获取周日
    $sunday_str = $timestr + (7-$now_day)*60*60*24;
    $sunday = date('Y-m-d', $sunday_str);

    for($i=0;$i<7;$i++)
    {
        $arr[$i]=date('Y-m-d',strtotime($monday.'+'.$i.'day'));
    }
    return $arr;
    // echo "星期一： $monday\n";
    // echo "星期天： $sunday\n";
}

function getDays()
{
    $timestr = time();    //当前时间戳
    $now_day = date('w',$timestr);  //当前是周几

    //获取周一
    $monday_str = $timestr - ($now_day-1)*60*60*24;
    $monday = date('Y-m-d', $monday_str);

    //获取周日
    $sunday_str = $timestr + (7-$now_day)*60*60*24;
    $sunday = date('Y-m-d', $sunday_str);

    for($i=0;$i<7;$i++)
    {
        $arr[$i]=strtotime($monday.'+'.$i.'day');
    }
    return $arr;
    // echo "星期一： $monday\n";
    // echo "星期天： $sunday\n";
}

//两个日期之间相差的天数
function diffBetweenTwoDays($day1, $day2)
{
    $second1 = strtotime($day1);
    $second2 = strtotime($day2);

    if ($second1 < $second2) {
        $tmp = $second2;
        $second2 = $second1;
        $second1 = $tmp;
    }
    return ($second1 - $second2) / 86400;
}

//设置缓存
function set_cache($key, $value, $date = 86400)
{
    Cache::set($key, $value, $date);
}

//读取缓存
function get_cache($key)
{
    return Cache::get($key);
}

//清空缓存
function clear_cache($key)
{
    Cache::clear($key);
}


//读取文件配置
function get_config($key)
{
    return Config::get($key);
}

//读取系统配置
function get_system_config($name,$key='')
{
    $config=[];
    if (get_cache('system_config' . $name)) {
        $config = get_cache('system_config' . $name);
    } else {
        $conf = Db::name('config')->where('name',$name)->find();
        if($conf['content']){
            $config = unserialize($conf['content']);
        }
        set_cache('system_config' . $name, $config);
    }
    if($key==''){
        return $config;
    }
    else{
        if($config[$key]){
            return $config[$key];
        }
    }
}
function upload_file($form_name = 'file', $save_dir = "", &$error = '')
{
    // 获取文件对象
    $files = \request()->file($form_name);
    // 判断是否有上传的文件
    if (!$files) {
        $error = "请选择文件";
        return false;
    }
    try {
        // 允许上传的后缀
        $allowext = 'xls,xlsx,doc,docx,ppt,pptx,zip,rar,mp3,txt,pdf,sql,js,css,chm,mp4';
        // 上传路径
        $save_dir = empty($save_dir) ? 'temp' : $save_dir;
        if (is_array($files)) {
            foreach ($files as $file) {
                $data = [];
                foreach ($files as $file) {
                    // 使用验证器验证上传的文件
                    validate(['file' => [
                        // 限制文件大小(单位b)，这里限制为4M
                        'filesize' => 10 * 1024 * 1024,
                        // 限制文件后缀，多个后缀以英文逗号分割
                        'fileExt' => $allowext,
                    ]])->check(['file' => $file]);
                    // 上传到本地服务器
                    $savename = Filesystem::putFile($save_dir, $file);
                    if ($savename) {
                        // 拼接路径
                        $path = str_replace('\\', '/', '/' . $savename);
                        $data[] = [
                            'fileName' => $file->getOriginalName(),
                            'filePath' => $path,
                        ];
                    }
                }
                return $data;
            }
        } else {
            // 使用验证器验证上传的文件
            validate(['file' => [
                // 限制文件大小(单位b)，这里限制为4M
                'filesize' => 1000 * 1024 * 1024,
                // 限制文件后缀，多个后缀以英文逗号分割
                'fileExt' => $allowext,
            ]])->check(['file' => $files]);
            // 上传到本地服务器
            $savename = \think\facade\Filesystem::disk('public')->putFile($save_dir, $files);
            if ($savename) {
                $path = get_config('filesystem.disks.public.url');
                $filepath = $path . '/' . $savename;

                // 拼接路径
                $path = str_replace('\\', '/', '/' . $filepath);
                $path = substr($path,1);

                $result = [
//                        'fileName' => $files->getOriginalName(),
                    'filePath' => $path,
                ];
                return $result;
            }
        }
    } catch (ValidateException $e) {
        // 上传校验失败
        $error = $e->getMessage();
    } catch (Exception $e) {
        // 上传异常
        $error = $e->getMessage();
    }
}
function upload_image($form_name = 'file', $save_dir = "", &$error = '')
{
    // 获取文件对象
    $files = \request()->file($form_name);
    // 判断是否有上传的文件
    if (!$files) {
        $error = "请选择图片";
        return false;
    }

    try {
        // 允许上传的后缀
        $allowext = 'gif,GIF,jpg,JPG,jpeg,JPEG,png,PNG,bmp,BMP,xls,xlsx,doc,docx,ppt,pptx,zip,rar,mp3,txt,pdf,sql,js,css,chm,mp4';
        // 上传路径
        $save_dir = empty($save_dir) ? 'temp' : $save_dir;

        if (is_array($files)) {
            $data = [];
            foreach ($files as $file) {
                // 使用验证器验证上传的文件
                validate(['file' => [
                    // 限制文件大小(单位b)，这里限制为4M
                    'filesize' => 100 * 1024 * 1024,
                    // 限制文件后缀，多个后缀以英文逗号分割
                    'fileExt' => $allowext,
                ]])->check(['file' => $file]);
                // 上传到本地服务器
                $savename = Filesystem::putFile($save_dir, $file);

                if ($savename) {
                    // 拼接路径
                    $path = str_replace('\\', '/', '/' . $savename);

//                        $data[] = [
//                            'filepath' => $path,
//                            'filename' => $file->getOriginalName(),
//                            'fileext' => $file->extension(),
//                            'filesize' => $file->getSize(),
//                        ];
                    $data[] = $path;
                }
            }
            return $data;
        } else {
            // 使用验证器验证上传的文件
            validate(['file' => [
                // 限制文件大小(单位b)，这里限制为4M
                'filesize' => 10 * 1024 * 1024,
                // 限制文件后缀，多个后缀以英文逗号分割
                'fileExt' => $allowext,
            ]])->check(['file' => $files]);
            // 上传到本地服务器
            $dataPath = date('Ym');
            $savename = \think\facade\Filesystem::disk('public')->putFile($save_dir, $files);

            if ($savename) {
                $path = get_config('filesystem.disks.public.url');
                $filepath = $path . '/' . $savename;

                // 拼接路径
                $path = str_replace('\\', '/', '/' . $filepath);
                $path = substr($path,1);
//                    $data = [
//                        'filepath' => $path,
//                        'filename' => $files->getOriginalName(),
//                        'fileext' => $files->extension(),
//                        'filesize' => $files->getSize(),
//                    ];
                return $path;
            }
        }
    } catch (ValidateException $e) {
        // 上传校验失败
        $error = $e->getMessage();
    } catch (Exception $e) {
        // 上传异常
        $error = $e->getMessage();
    }
    return false;
}

/**
 * 时间戳转日期格式
 * @param int $time 时间戳
 * @param string $format 转换格式(默认：Y-m-d h:i:s)
 * @return false|string 返回结果
 * @author 牧羊人
 * @date 2020-04-21
 */
function datetime($time, $format = 'Y-m-d H:i:s')
{
    if (empty($time)) {
        return '--';
    }
    $time = is_numeric($time) ? $time : strtotime($time);
    return date($format, $time);
}

//系统信息
function get_system_info($key)
{
    $system = [
        'os' => PHP_OS,
        'php' => PHP_VERSION,
        'upload_max_filesize' => get_cfg_var("upload_max_filesize") ? get_cfg_var("upload_max_filesize") : "不允许上传附件",
        'max_execution_time' => get_cfg_var("max_execution_time") . "秒 ",
    ];
    if (empty($key)) {
        return $system;
    } else {
        return $system[$key];
    }
}

//获取url参数
function get_params($key = "")
{
    return Request::instance()->param($key);
}

//生成一个不会重复的字符串
function make_token()
{
    $str = md5(uniqid(md5(microtime(true)), true));
    $str = sha1($str); //加密
    return $str;
}

//随机字符串，默认长度10
function set_salt($num = 10)
{
    $str = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890';
    $salt = substr(str_shuffle($str), 10, $num);
    return $salt;
}
//密码加密
function set_password($pwd, $salt)
{
    return md5(md5($pwd . $salt) . $salt);
}

//判断cms是否完成安装
function is_installed()
{
    static $isInstalled;
    if (empty($isInstalled)) {
        $isInstalled = file_exists(CMS_ROOT . 'config/install.lock');
    }
    return $isInstalled;
}

//判断cms是否存在模板
function isTemplate($url='')
{
    static $isTemplate;
    if (empty($isTemplate)) {
        $isTemplate = file_exists(CMS_ROOT . 'app/'.$url);
    }
    return $isTemplate;
}

/**
 * 返回json数据，用于接口
 * @param    integer    $code
 * @param    string     $msg
 * @param    array      $data
 * @param    string     $url
 * @param    integer    $httpCode
 * @param    array      $header
 * @param    array      $options
 * @return   json
 */
function to_assign($code = 0, $msg = "操作成功", $data = [], $url = '', $httpCode = 200, $header = [], $options = [])
{
    $res = ['code' => $code];
    $res['msg'] = $msg;
    $res['url'] = $url;
    if (is_object($data)) {
        $data = $data->toArray();
    }
    $res['data'] = $data;
    $response = \think\Response::create($res, "json", $httpCode, $header, $options);
    throw new \think\exception\HttpResponseException($response);
}

/**
 * 计算中奖概率
 * @param $proArr
 * @return int
 */
function getRand($proArr)
{
    $result = '';
    //概率数组的总概率精度
    $proSum = array_sum($proArr);
    //概率数组循环
    foreach ($proArr as $key => $proCur) {
        $randNum = mt_rand(1, $proSum);
        if ($randNum <= $proCur) {
            $result = $key;
            break;
        } else {
            $proSum -= $proCur;
        }
    }
    unset($proArr);
    return $result;
}

/**
 * 适配layui数据列表的返回数据方法，用于接口
 * @param    integer    $code
 * @param    string     $msg
 * @param    array      $data
 * @param    integer    $httpCode
 * @param    array      $header
 * @param    array      $options
 * @return   json
 */
function table_assign($code = 0, $msg = '请求成功', $data = [], $httpCode = 200, $header = [], $options = [])
{
    $res['code'] = $code;
    $res['msg'] = $msg;
    if (is_object($data)) {
        $data = $data->toArray();
    }
    if (!empty($data['total'])) {
        $res['count'] = $data['total'];
    } else {
        $res['count'] = 0;
    }
    $res['data'] = $data['data'];
    $response = \think\Response::create($res, "json", $httpCode, $header, $options);
    throw new \think\exception\HttpResponseException($response);
}

function get_image_url($image_url)
{
    return \request()->domain() . $image_url;
}

//菜单转为父子菜单
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'list', $root = 0)
{
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[$data[$pk]] = &$list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = &$refer[$parentId];
                    $parent[$child][$data[$pk]] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}
/**
 * 时间戳格式化
 * @param int    $time
 * @param string $format 默认'Y-m-d H:i'，x代表毫秒
 * @return string 完整的时间显示
 */
function time_format($time = NULL, $format = 'Y-m-d H:i:s')
{
    $usec = $time = $time === null ? '' : $time;
    if (strpos($time, '.')!==false) {
        list($usec, $sec) = explode(".", $time);
    } else {
        $sec = 0;
    }

    return $time != '' ? str_replace('x', $sec, date($format, intval($usec))) : '';
}

function get_random_str($length = 8, $type = 0)
{
    $a = 'abcdefghijklmnopqrstuvwxyz';
    $A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $n = '0123456789';

    switch ($type) {
        case 1:
            $chars = $a;
            break;
        case 2:
            $chars = $A;
            break;
        case 3:
            $chars = $n;
            break;
        case 4:
            $chars = $a . $A;
            break;
        case 5:
            $chars = $a . $A . $n;
            break;
        default:
            $chars = $a . $n;
    }

    $str = '';
    for ($i = 0; $i < $length; $i++) {
        $str .= $chars[mt_rand(0, strlen($chars) - 1)];
    }
    return $str;
}

function curl_get($url, $data = [])
{
    // 处理get数据
    if (!empty($data)) {
        $url = $url . '?' . http_build_query($data);
    }
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}

function curl_post($url, $data = [])
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}


/**
 * 根据附件表的id返回url地址
 * @param  [type] $id [description]
 */
function get_file($id)
{
    if ($id) {
        $geturl = \think\facade\Db::name("file")->where(['id' => $id])->find();

        if ($geturl['status'] == 1) {
            //审核通过
            //获取签名的URL
            $url = $geturl['filepath'];
            return $url;
        } elseif ($geturl['status'] == 0) {
            //待审核
            return '/static/admin/images/nonepic360x360.jpg';
        } else {
            //不通过
            return '/static/admin/images/nonepic360x360.jpg';
        }
    }
    return false;
}

function get_file_list($dir)
{
    $list=[];
    if(is_dir($dir)){
        $info = opendir($dir);
        while (($file = readdir($info)) !== false) {
            //echo $file.'<br>';
            $pathinfo=pathinfo($file);
            if($pathinfo['extension']=='html'){   //只获取符合后缀的文件
                array_push($list, $pathinfo);
            }
        }
        closedir($info);
    }
    return $list;
}

//获取当前登录用户的信息
function get_login_user($key = "")
{
    $session_user = get_config('app.session_user');
    if (\think\facade\Session::has($session_user)) {
        $gougu_user = \think\facade\Session::get($session_user);
        if (!empty($key)) {
            if (isset($gougu_user[$key])) {
                return $gougu_user[$key];
            } else {
                return '';
            }
        } else {
            return $gougu_user;
        }
    } else {
        return '';
    }
}

/**
 * 判断访客是否是蜘蛛
 */
function isRobot($except = '') {
    $ua = strtolower ( $_SERVER ['HTTP_USER_AGENT'] );
    $botchar = "/(baidu|google|spider|soso|yahoo|sohu-search|yodao|robozilla|AhrefsBot)/i";
    $except ? $botchar = str_replace ( $except . '|', '', $botchar ) : '';
    if (preg_match ( $botchar, $ua )) {
        return true;
    }
    return false;
}

/**
 * 客户操作日志
 * @param string $type 操作类型 login reg add edit view delete down join sign play order pay
 * @param string    $param_str 操作内容
 * @param int    $param_id 操作内容id
 * @param array  $param 提交的参数
 */
function add_user_log($type, $param_str = '', $param_id = 0, $param = [])
{
    $request = request();
    $title = '未知操作';
    $type_action = get_config('log.user_action');
    if($type_action[$type]){
        $title = $type_action[$type];
    }
    if ($type == 'login') {
        $login_user = \think\facade\Db::name('User')->where(array('id' => $param_id))->find();
        if ($login_user['nickname'] == '') {
            $login_user['nickname'] = $login_user['name'];
        }
        if ($login_user['nickname'] == '') {
            $login_user['nickname'] = $login_user['username'];
        }
    } else {
        $login_user = get_login_user();
        if (empty($login_user)) {
            $login_user = [];
            $login_user['id'] = 0;
            $login_user['nickname'] = '游客';
            if(isRobot()){
                $login_user['nickname'] = '蜘蛛';
                $type = 'spider';
                $title = '爬行';
            }
        } else {
            if ($login_user['nickname'] == '') {
                $login_user['nickname'] = $login_user['username'];
            }
        }
    }
    $content = $login_user['nickname'] . '在' . date('Y-m-d H:i:s') . '执行了' . $title . '操作';
    if ($param_str != '') {
        $content = $login_user['nickname'] . '在' . date('Y-m-d H:i:s') . $title . '了' . $param_str;
    }
    $data = [];
    $data['uid'] = $login_user['id'];
    $data['nickname'] = $login_user['nickname'];
    $data['type'] = $type;
    $data['title'] = $title;
    $data['content'] = $content;
    $data['param_id'] = $param_id;
    $data['param'] = json_encode($param);
    $data['module'] = strtolower(app('http')->getName());
    $data['controller'] = strtolower(app('request')->controller());
    $data['function'] = strtolower(app('request')->action());
    $data['ip'] = app('request')->ip();
    $data['create_time'] = time();
    \think\facade\Db::name('UserLog')->strict(false)->field(true)->insert($data);
}

/**
 * 邮件发送
 * @param $to    接收人
 * @param string $subject 邮件标题
 * @param string $content 邮件内容(html模板渲染后的内容)
 * @throws Exception
 * @throws phpmailerException
 */
function send_email($to, $subject = '', $content = '')
{
    $mail = new PHPMailer\PHPMailer\PHPMailer();
    $email_config = \think\facade\Db::name('config')
        ->where('name', 'email')
        ->find();
    $config = unserialize($email_config['content']);

    $mail->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->isSMTP();
    $mail->SMTPDebug = 0;

    //调试输出格式
    //$mail->Debugoutput = 'html';
    //smtp服务器
    $mail->Host = $config['smtp'];
    //端口 - likely to be 25, 465 or 587
    $mail->Port = $config['smtp_port'];
    if($mail->Port == '465'){
        $mail->SMTPSecure = 'ssl';// 使用安全协议
    }
    //Whether to use SMTP authentication
    $mail->SMTPAuth = true;
    //发送邮箱
    $mail->Username = $config['smtp_user'];
    //密码
    $mail->Password = $config['smtp_pwd'];
    //Set who the message is to be sent from
    $mail->setFrom($config['email'], $config['from']);
    //回复地址
    //$mail->addReplyTo('replyto@example.com', 'First Last');
    //接收邮件方
    if (is_array($to)) {
        foreach ($to as $v) {
            $mail->addAddress($v);
        }
    } else {
        $mail->addAddress($to);
    }

    $mail->isHTML(true);// send as HTML
    //标题
    $mail->Subject = $subject;
    //HTML内容转换
    $mail->msgHTML($content);
    $status = $mail->send();
    if ($status) {
        return true;
    } else {
        //  echo "Mailer Error: ".$mail->ErrorInfo;// 输出错误信息
        //  die;
        return false;
    }
}

/*
* 下划线转驼峰
* 思路:
* step1.原字符串转小写,原字符串中的分隔符用空格替换,在字符串开头加上分隔符
* step2.将字符串中每个单词的首字母转换为大写,再去空格,去字符串首部附加的分隔符.
*/
function camelize($uncamelized_words,$separator='_')
{
    $uncamelized_words = $separator. str_replace($separator, " ", strtolower($uncamelized_words));
    return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator );
}

/**
 * 驼峰命名转下划线命名
 * 思路:
 * 小写和大写紧挨一起的地方,加上分隔符,然后全部转小写
 */
function uncamelize($camelCaps,$separator='_')
{
    return strtolower(preg_replace('/([a-z])([A-Z])/', "$1" . $separator . "$2", $camelCaps));
}
if (!function_exists('cdnurl')) {
    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $config = get_system_config("alioss");
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        if($config)
        {
            $cdnurl = $config['cdnurl']?'http://'.$config['cdnurl']:Request::instance()->domain();
        }
        else
        {
            $cdnurl = Request::instance()->domain();
        }
        $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}